﻿using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.ContentManagement.Handlers;
using Orchard.ExternalAlbum.Models;

namespace Orchard.ExternalAlbum.Drivers
{
    public class PicasaAlbumPartDriver : ContentPartDriver<PicasaAlbumPart>
    {
        protected override string Prefix
        {
            get { return "PicasaAlbum"; }
        }

        protected override DriverResult Editor(PicasaAlbumPart part, dynamic shapeHelper)
        {
            return ContentShape("Parts_PicasaAlbum_Edit", () => shapeHelper
                .EditorTemplate(TemplateName: "Parts/PicasaAlbum", Model: part, Prefix: Prefix));
        }

        protected override DriverResult Editor(PicasaAlbumPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part, Prefix, null, null);
            return Editor(part, shapeHelper);
        }

        protected override DriverResult Display(PicasaAlbumPart part, string displayType, dynamic shapeHelper)
        {
            return ContentShape("Parts_PicasaAlbum",
                () => shapeHelper.Parts_PicasaAlbum(
                    UserID: part.UserID,
                    AlbumID: part.AlbumID,
                    AuthKey: part.AuthKey
                    ));
        }

        protected override void Importing(PicasaAlbumPart part, ImportContentContext context)
        {
            var userID = context.Attribute(part.PartDefinition.Name, "UserID");
            if (userID != null)
                part.Record.UserID = userID;

            var albumID = context.Attribute(part.PartDefinition.Name, "AlbumID");
            if (albumID != null)
                part.Record.AlbumID = albumID;

            var authKey = context.Attribute(part.PartDefinition.Name, "AuthKey");
            if (authKey != null)
                part.Record.AuthKey = authKey;
        }

        protected override void Exporting(PicasaAlbumPart part, ExportContentContext context)
        {
            context.Element(part.PartDefinition.Name).SetAttributeValue("UserID", part.Record.UserID);
            context.Element(part.PartDefinition.Name).SetAttributeValue("AlbumID", part.Record.AlbumID);
            context.Element(part.PartDefinition.Name).SetAttributeValue("AuthKey", part.Record.AuthKey);
        }
    }
}
